package logic

import (
	"context"
	"errors"
	"math/rand"
	"strconv"
	"time"
	"video/models/cache"
	"video/pkg"
	"video/videorpc/internal/svc"
	"video/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 验证码
func (l *SendSmsLogic) SendSms(in *videorpc.SendSmsRequest) (*videorpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line
	code := rand.Intn(9000) + 1000
	i, err := cache.Rdb.Get(l.ctx, "data"+in.Phone).Int64()
	if i >= 1 {
		return nil, errors.New("验证码已过期，请重新获取")
	}
	sms, err := pkg.SendSms(in.Phone, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}
	if sms.Code != 2 {
		return nil, errors.New("短信发送失败，请重试")
	}
	cache.Rdb.Set(l.ctx, "sendSms"+in.Phone, code, time.Minute*5)
	//cache.Rdb.Set(l.ctx, "data"+in.Phone, 1, time.Minute*1)
	return &videorpc.SendSmsResponse{
		Code: strconv.Itoa(code),
	}, nil
}
